# coding:utf-8
import joblib
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from tqdm import tqdm
import tkinter as tk
from tkinter import messagebox, ttk  # 新增GUI库

# ... 原有createModel、loadModel函数保持不变 ...

def create_gui():
    """创建图形用户界面"""
    # 初始化主窗口
    root = tk.Tk()
    root.title("乳腺癌肿瘤分类预测系统")
    root.geometry("650x500")  # 窗口尺寸

    # 特征列表（顺序必须与训练时一致）
    features = [
        'Clump Thickness',
        'Uniformity of Cell Size',
        'Uniformity of Cell Shape',
        'Marginal Adhesion',
        'Single Epithelial Cell Size',
        'Bare Nuclei',
        'Bland Chromatin',
        'Normal Nucleoli',
        'Mitoses'
    ]

    # 创建输入组件（标签+输入框）
    input_entries = {}  # 存储输入框对象
    for i, feature in enumerate(features):
        # 特征标签
        tk.Label(root, text=f"{feature}（1-10）:", font=('微软雅黑', 10)).grid(
            row=i, column=0, padx=15, pady=8, sticky='e'
        )
        # 输入框（限制只能输入数字）
        entry = ttk.Entry(root, width=12)
        entry.grid(row=i, column=1, padx=10, pady=8)
        # 绑定输入验证（仅允许数字）
        entry['validate'] = 'key'
        entry['validatecommand'] = (entry.register(lambda x: x.isdigit()), '%P')
        input_entries[feature] = entry

    # 结果显示标签
    result_label = tk.Label(root, text="", font=('黑体', 14), wraplength=500)
    result_label.grid(row=len(features)+1, column=0, columnspan=2, pady=20)

    def predict_click():
        """预测按钮点击事件处理"""
        try:
            # 加载模型和标准化器
            model = joblib.load('logistic_regression_model.pkl')
            scaler = joblib.load('scaler.pkl')
        except FileNotFoundError:
            messagebox.showerror("错误", "未找到模型文件，请先运行生成模型！")
            return

        # 读取并验证输入数据
        input_data = {}
        for feature, entry in input_entries.items():
            value = entry.get().strip()
            if not value:
                messagebox.showerror("输入错误", f"请填写 {feature}")
                return
            if not (1 <= int(value) <= 10):
                messagebox.showerror("输入错误", f"{feature} 需为1-10的整数")
                return
            input_data[feature] = [int(value)]  # 转换为模型需要的格式

        # 数据标准化并预测
        user_df = pd.DataFrame(input_data)
        user_scaled = scaler.transform(user_df)
        pred = model.predict(user_scaled)

        # 转换为中文结果并显示（良性绿色，恶性红色）
        result = "良性" if pred[0] == 2 else "恶性"
        result_label.config(
            text=f"预测结果：该乳腺肿瘤样本为 {result}",
            fg='green' if result == '良性' else 'red'
        )

    # 创建预测按钮
    ttk.Button(root, text="立即预测", command=predict_click, style='TButton', width=20).grid(
        row=len(features), column=0, columnspan=2, pady=15
    )

    root.mainloop()

# 启动图形界面（替换原有命令行菜单）
if __name__ == "__main__":
    create_gui()
